package web

import (
	"context"
	"gitee.com/wochong/HalloGin/database/sqlite3"
	"gitee.com/wochong/HalloGin/model"
	conf "gitee.com/wochong/HalloGin/package/config"
	"gitee.com/wochong/HalloGin/router"
	"github.com/golang/glog"
	"net/http"
)

var (
	srv *http.Server
)

//Init 初始化WEB api
func Init(path, version string) {

	conf.LoadConfOrDie(path, version)

	config := conf.Get()

	db := sqlite3.OpenSqlite3()

	model.Init(db)

	glog.V(2).Infoln("Init Database SUCCESS.")

	routers := router.SetupRouter() // 创建路由

	glog.Infoln("Init Router SUCCESS.\n")

	srv = &http.Server{Addr: config.APIAddr, Handler: routers}

	glog.V(1).Infof("Server Listen At:  [%s]  ...\n\n", config.APIAddr)
}

//StartContext 启动master 节点
func StartContext(ctx context.Context) {

	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil {
			glog.Warningln("API server 退出: ", err)
		}
	}()

}

//GracefulStop exit
func GracefulStop() {
	srv.Shutdown(nil)
	glog.V(2).Infoln("HTTP Server exited.")

	// model.Close()
}
